package com.example.course

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import java.io.Serializable
import java.util.ArrayList

class MainActivity : AppCompatActivity() {
    private lateinit var day: RelativeLayout
    private val databaseHelper = DatabaseHelper(this, "database.db", null, 1)
    private var clickedView: View? = null
    private var currentCoursesNumber = 0
    private var maxCoursesNumber = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(findViewById(R.id.toolbar))
        loadData()
    }

    private fun loadData() {
        val coursesList = ArrayList<Course>()
        val sqLiteDatabase = databaseHelper.writableDatabase
        val cursor = sqLiteDatabase.rawQuery("select * from courses", null)
        if (cursor.moveToFirst()) {
            val courseNameIndex = cursor.getColumnIndex("course_name")
            val teacherIndex = cursor.getColumnIndex("teacher")
            val classRoomIndex = cursor.getColumnIndex("class_room")
            val dayIndex = cursor.getColumnIndex("day")
            val classStartIndex = cursor.getColumnIndex("class_start")
            val classEndIndex = cursor.getColumnIndex("class_end")

            do {
                if (courseNameIndex != -1 && teacherIndex != -1 && classRoomIndex != -1 && dayIndex != -1 && classStartIndex != -1 && classEndIndex != -1) {
                    coursesList.add(Course(
                        cursor.getString(courseNameIndex),
                        cursor.getString(teacherIndex),
                        cursor.getString(classRoomIndex),
                        cursor.getInt(dayIndex),
                        cursor.getInt(classStartIndex),
                        cursor.getInt(classEndIndex)
                    ))
                }
            } while (cursor.moveToNext())
        }
        cursor.close()

        for (course in coursesList) {
            createLeftView(course)
            createItemCourseView(course)
        }
    }

    private fun saveData(course: Course) {
        val sqLiteDatabase = databaseHelper.writableDatabase
        val cursor = sqLiteDatabase.rawQuery(
            "SELECT * FROM courses WHERE day = ? AND class_start < ? AND class_end > ?",
            arrayOf(course.day.toString(), course.classEnd.toString(), course.classStart.toString())
        )

        if (cursor.moveToFirst()) {
            Toast.makeText(this, "该时间段已有课程，发生冲突", Toast.LENGTH_SHORT).show()
        } else {
            sqLiteDatabase.execSQL(
                "INSERT INTO courses(course_name, teacher, class_room, day, class_start, class_end) VALUES(?, ?, ?, ?, ?, ?)",
                arrayOf(course.courseName, course.teacher, course.classRoom, course.day.toString(), course.classStart.toString(), course.classEnd.toString())
            )
            Toast.makeText(this, "课程添加成功", Toast.LENGTH_SHORT).show()
        }
        cursor.close()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.toolbar, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.add_courses -> {
                val intent = Intent(this, AddCourseActivity::class.java)
                startActivityForResult(intent, 0)
                true
            }
            R.id.menu_about -> {
                val intent = Intent(this, AboutActivity::class.java)
                startActivity(intent)
                true
            }
            R.id.search_courses -> {
                showSearchDialog()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null) {
            val course = data.getSerializableExtra("course") as Course
            createLeftView(course)
            createItemCourseView(course)
            saveData(course)
        }

        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            val preCourse = data.getSerializableExtra("PreCourse") as Course
            val isDelete = data.getBooleanExtra("isDelete", true)

            if (isDelete) {
                clickedView?.visibility = View.GONE
                day = getViewDay(preCourse.day)
                day.removeView(clickedView)
                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
            } else {
                val newCourse = data.getSerializableExtra("newCourse") as Course
                clickedView?.visibility = View.GONE
                day = getViewDay(preCourse.day)
                day.removeView(clickedView)

                createLeftView(newCourse)
                createItemCourseView(newCourse)
            }
        }

        if (requestCode == 2 && resultCode == Activity.RESULT_OK && data != null) {
            val preCourse = data.getSerializableExtra("PreCourse") as Course
            val newCourse = data.getSerializableExtra("newCourse") as Course

            clickedView?.visibility = View.GONE
            day = getViewDay(preCourse.day)
            day.removeView(clickedView)

            createLeftView(newCourse)
            createItemCourseView(newCourse)
        }
    }

    private fun createLeftView(course: Course) {
        val endNumber = course.classEnd
        if (endNumber > maxCoursesNumber) {
            for (i in 0 until endNumber - maxCoursesNumber) {
                val view = LayoutInflater.from(this).inflate(R.layout.left_view, null)
                val params = LinearLayout.LayoutParams(110, 180)
                view.layoutParams = params

                val text = view.findViewById<TextView>(R.id.class_number_text)
                text.text = (++currentCoursesNumber).toString()

                val leftViewLayout = findViewById<LinearLayout>(R.id.left_view_layout)
                leftViewLayout.addView(view)
            }
            maxCoursesNumber = endNumber
        }
    }

    private fun getViewDay(day: Int): RelativeLayout {
        val dayId = when (day) {
            1 -> R.id.monday
            2 -> R.id.tuesday
            3 -> R.id.wednesday
            4 -> R.id.thursday
            5 -> R.id.friday
            6 -> R.id.saturday
            7 -> R.id.weekday
            else -> throw IllegalArgumentException("Invalid day of week")
        }
        return findViewById(dayId)
    }

    private fun createItemCourseView(course: Course) {
        val getDay = course.day
        if (getDay < 1 || getDay > 7 || course.classStart > course.classEnd) {
            Toast.makeText(this, "课程结束时间比开始时间还早~~", Toast.LENGTH_LONG).show()
        } else {
            day = getViewDay(getDay)

            val height = 180
            val v = LayoutInflater.from(this).inflate(R.layout.course_card, null)
            v.y = height * (course.classStart - 1).toFloat()
            val params = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                (course.classEnd - course.classStart + 1) * height - 8
            )
            v.layoutParams = params
            val text = v.findViewById<TextView>(R.id.text_view)
            text.text = "${course.courseName}\n${course.teacher}\n${course.classRoom}"
            day.addView(v)

            v.setOnClickListener {
                clickedView = v
                val intent = Intent(this, SeeCourseActivity::class.java)
                intent.putExtra("seeCourse", course as Serializable)
                startActivityForResult(intent, 1)
            }
        }
    }

    private fun showSearchDialog() {
        val dialogView = layoutInflater.inflate(R.layout.search_dialog, null)
        val searchQuery = dialogView.findViewById<EditText>(R.id.search_query)
        val searchButton = dialogView.findViewById<Button>(R.id.search_button)

        val dialog = AlertDialog.Builder(this)
            .setTitle("Search Courses")
            .setView(dialogView)
            .create()

        searchButton.setOnClickListener {
            val query = searchQuery.text.toString()
            if (query.isNotEmpty()) {
                searchCourses(query)
                dialog.dismiss()
            } else {
                Toast.makeText(this, "Please enter a search query", Toast.LENGTH_SHORT).show()
            }
        }

        dialog.show()
    }

    private fun searchCourses(query: String) {
        val coursesList = ArrayList<Course>()
        val sqLiteDatabase = databaseHelper.writableDatabase
        val cursor = sqLiteDatabase.rawQuery("SELECT * FROM courses WHERE course_name LIKE ?", arrayOf("%$query%"))
        if (cursor.moveToFirst()) {
            val courseNameIndex = cursor.getColumnIndex("course_name")
            val teacherIndex = cursor.getColumnIndex("teacher")
            val classRoomIndex = cursor.getColumnIndex("class_room")
            val dayIndex = cursor.getColumnIndex("day")
            val classStartIndex = cursor.getColumnIndex("class_start")
            val classEndIndex = cursor.getColumnIndex("class_end")

            do {
                if (courseNameIndex != -1 && teacherIndex != -1 && classRoomIndex != -1 && dayIndex != -1 && classStartIndex != -1 && classEndIndex != -1) {
                    coursesList.add(Course(
                        cursor.getString(courseNameIndex),
                        cursor.getString(teacherIndex),
                        cursor.getString(classRoomIndex),
                        cursor.getInt(dayIndex),
                        cursor.getInt(classStartIndex),
                        cursor.getInt(classEndIndex)
                    ))
                }
            } while (cursor.moveToNext())
        }
        cursor.close()

        if (coursesList.isEmpty()) {
            Toast.makeText(this, "No courses found", Toast.LENGTH_SHORT).show()
        } else {
            val intent = Intent(this, SeeCourseActivity::class.java)
            intent.putExtra("seeCourse", coursesList[0] as Serializable)
            startActivity(intent)
        }
    }
}